package com.enation.app.javashop.seller.api.goods;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.enation.app.javashop.core.base.message.GoodsChangeMsg;
import com.enation.app.javashop.core.base.rabbitmq.AmqpExchange;
import com.enation.app.javashop.core.goods.GoodsErrorCode;
import com.enation.app.javashop.core.goods.model.dos.GoodsSkuDO;
import com.enation.app.javashop.core.goods.model.dos.SpecValuesDO;
import com.enation.app.javashop.core.goods.model.dto.GoodsQueryParam;
import com.enation.app.javashop.core.goods.model.vo.*;
import com.enation.app.javashop.core.goods.service.GoodsManager;
import com.enation.app.javashop.framework.context.UserContext;
import com.enation.app.javashop.framework.database.Page;
import com.enation.app.javashop.framework.exception.ServiceException;
import com.enation.app.javashop.framework.security.model.Seller;
import com.enation.app.javashop.framework.util.BeanUtil;
import com.google.common.collect.Maps;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import com.enation.app.javashop.core.goods.service.GoodsQueryManager;
import com.enation.app.javashop.core.goods.service.GoodsSkuManager;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;

/**
 * 商品sku控制器
 * 
 * @author fk
 * @version v2.0
 * @since v7.0.0 2018-03-21 11:48:40
 */
@RestController
@RequestMapping("/seller/goods")
@Api(description = "商品sku相关API")
public class GoodsSkuSellerController {

	@Autowired
	private GoodsQueryManager goodsQueryManager;

	@Autowired
	private GoodsSkuManager goodsSkuManager;

	@Autowired
	private GoodsManager goodsManager;

	@Autowired
	private AmqpTemplate amqpTemplate;

	@ApiOperation(value = "商品sku信息信息获取api")
	@ApiImplicitParam(name	= "goods_id", value = "商品id",	required = true, dataType = "int",	paramType =	"path")
	@GetMapping("/{goods_id}/skus")
	public List<GoodsSkuVO> queryByGoodsId(@PathVariable(name = "goods_id") Integer goodsId) {

		CacheGoods goods = goodsQueryManager.getFromCache(goodsId);

		return  goods.getSkuList();
	}

	@ApiOperation(value = "APP 查询 商品sku信息")
	@ApiImplicitParam(name	= "goods_id", value = "商品id",	required = true, dataType = "int",	paramType =	"path")
	@GetMapping("/app/{goods_id}/skus")
	public Map<String, Object> appQueryByGoodsId(@PathVariable(name = "goods_id") Integer goodsId) {
		Map<String, Object> result = Maps.newHashMap();
		CacheGoods goods = goodsQueryManager.getFromCache(goodsId);
		List<GoodsSkuVO> skuList = goods.getSkuList();
		result.put("sku_list",skuList);
		List<SpecValueVO> specAll = new ArrayList<>();
		for (GoodsSkuVO goodsSkuVO : skuList) {
			List<SpecValueVO> specList = goodsSkuVO.getSpecList();
			if(!CollectionUtils.isEmpty(specList)){
				specAll.addAll(specList);
			}
		}

		specAll=specAll.stream().distinct().collect(Collectors.toList());

		Map<Integer, List<SpecValueVO>> specGroup = specAll.stream().distinct().collect(Collectors.groupingBy(SpecValueVO::getSpecId));
		List<SpecificationVO> specificationList = new ArrayList<>();

		for (Map.Entry<Integer, List<SpecValueVO>> entry : specGroup.entrySet()) {
			List<SpecValueVO> valueVOList = entry.getValue();
			List<SpecValuesDO> values = new ArrayList<>();
			for (SpecValueVO specValueVO : valueVOList) {
				SpecValuesDO specValuesDO = new SpecValuesDO();
				BeanUtil.copyProperties(specValueVO,specValuesDO);
				values.add(specValuesDO);
			}
			SpecValueVO specValueVO = valueVOList.get(0);
			SpecificationVO specificationVO = new SpecificationVO();
			specificationVO.setSpecId(specValueVO.getSpecId());
			specificationVO.setSpecName(specValueVO.getSpecName());
			specificationVO.setValueList(values);
			specificationList.add(specificationVO);
		}
		result.put("spec_info",specificationList);
		return result;
	}



	@GetMapping(value = "/skus/{sku_ids}/details")
	@ApiOperation(value = "查询多个商品的基本信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "sku_ids", value = "要查询的SKU主键", required = true, dataType = "int", paramType = "path",allowMultiple = true) })
	public List<GoodsSkuVO> getGoodsDetail(@PathVariable("sku_ids") Integer[] skuIds) {

		return this.goodsSkuManager.query(skuIds);
	}


	@ApiOperation(value = "查询SKU列表", response = GoodsSkuVO.class)
	@GetMapping("/skus")
	public Page list(GoodsQueryParam param, @ApiIgnore Integer pageNo, @ApiIgnore Integer pageSize) {
		param.setPageNo(pageNo);
		param.setPageSize(pageSize);
		param.setSellerId(UserContext.getSeller().getSellerId());
		param.setMarketEnable(null);
		param.setIsAuth(null);
		param.setDisabled(1);
		return this.goodsSkuManager.list(param);
	}


	@ApiOperation(value = "更新sku价格", notes = "更新sku价格")
	@ApiImplicitParams({
			@ApiImplicitParam(name	= "goods_id", value = "商品id",	required = true, dataType = "int",	paramType =	"path"),
			@ApiImplicitParam(name	= "sku_list", value = "sku数值", required = true, dataType = "GoodsSkuDO",	paramType =	"body",allowMultiple = true),
	})
	@PutMapping("/{goods_id}/updateCost")
	public Map updateQuantity(@ApiIgnore@Valid @RequestBody List<GoodsSkuDO>  skuList, @PathVariable("goods_id")Integer goodsId)  {

		CacheGoods goods = goodsQueryManager.getFromCache(goodsId);

		Seller seller = UserContext.getSeller();
		if (goods == null || !goods.getSellerId().equals(seller.getSellerId())) {
			throw new ServiceException(GoodsErrorCode.E307.code(), "没有操作权限");
		}

		for (GoodsSkuDO goodsSkuDO : skuList) {
			if (goodsSkuDO.getCost() == null) {
				continue;
			}
			this.goodsSkuManager.updateCost(goodsSkuDO);
		}

		Double price = skuList.get(0).getPrice();
		this.goodsManager.updateGoodsPrice(goodsId,price);

		// 发送增加商品消息，店铺增加自身商品数量，静态页使用
		GoodsChangeMsg goodsChangeMsg = new GoodsChangeMsg(new Integer[]{goodsId}, GoodsChangeMsg.UPDATE_OPERATION);
		//修改商品时需要删除商品参与的促销活动
		goodsChangeMsg.setDelPromotion(true);
		this.amqpTemplate.convertAndSend(AmqpExchange.GOODS_CHANGE, AmqpExchange.GOODS_CHANGE + "_ROUTING", goodsChangeMsg);

		// 清理redis数据
		goodsManager.cleanGoodsAssociated(goodsId,0);

		Map<String, Object> result = Maps.newHashMap();
		result.put("goods_price",price);
		return result;
	}
}
